/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.helper.web;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author My
 */
public class JsonHelper {
    
    public static Map parseJSON(String json) {
        json = prepareJsonString(json);
        String[] lines = json.split("\r\n");
        Map<String, String> parsedMap = new HashMap<>();
        
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            String[] pair = line.split(":");
            
            if (pair.length >= 2) {
                String key = clearString(pair[0]);
                String value = clearString(pair[1]);
                if (value != "{") {
                    parsedMap.put(key, value);
                }
            }
        }
        return parsedMap;
    }

    private static String clearString(String str) {
        str = str.trim();
        int ind0 = str.indexOf("\"");
        int ind1 = str.lastIndexOf("\"");
        if (ind0 != -1 && ind1 != -1) {
            str = str.substring(ind0 + 1, ind1);
        } else if (str.toCharArray()[str.length() - 1] == ',') {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
    
    //insert line spaces after "{", "}", ",", "[", "]" symbols
    private static String prepareJsonString(String stringJSON) {
        String jsonWithLineSpaces = stringJSON;
        jsonWithLineSpaces = jsonWithLineSpaces.replace("{", "{\r\n");
        jsonWithLineSpaces = jsonWithLineSpaces.replace(",", ",\r\n");
        jsonWithLineSpaces = jsonWithLineSpaces.replace("[", "[\r\n");
        jsonWithLineSpaces = jsonWithLineSpaces.replace("}", "}\r\n");
        jsonWithLineSpaces = jsonWithLineSpaces.replace("]", "]\r\n");
        return jsonWithLineSpaces;
    }
    
}
